package ddz.net;

import com.kaka.notice.Facade;
import com.kaka.notice.Message;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;

public class EventQueue {

    private final Queue<Message> queue = new ConcurrentLinkedQueue<>();
    private final Facade facade;
    private final AtomicBoolean doing;

    public EventQueue(Facade facade) {
        this.facade = facade;
        this.doing = new AtomicBoolean(false);
    }

    public void addEvent(Message event) {
        queue.add(event);
        if (doing.get()) return;
        doEvent();
    }

    private void doEvent() {
        if (queue.isEmpty()) {
            this.doing.set(false);
            return;
        }
        this.doing.set(true);
        final Message event = queue.poll();
        Executor threadPoll = facade.getThreadPool();
        threadPoll.execute(() -> {
            facade.sendMessage(event);
            doEvent();
        });
    }

}
